# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         api.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/18 17:32
# -------------------------------------------------------------------------------

import django_filters

from apps.HttpAutoTestService.models import Api

__all__ = ['ApiNameFilter', 'ApiFilter']


class ApiNameFilter(django_filters.rest_framework.FilterSet):
    """
    接口名称过滤
    """
    project = django_filters.CharFilter(field_name='project_id', lookup_expr='exact')
    module = django_filters.CharFilter(method='module_filter')
    detail = django_filters.CharFilter(method='detail_filter')

    def detail_filter(self, query_set, name, value):
        # 显示更详细的接口信息
        if value:
            query_set = query_set.values('id', 'name', 'url', 'method', 'request_params', 'headers', 'request_data',
                                         'request_data_type', 'parameter_desc', 'environment')
        return query_set

    def module_filter(self, query_set, name, value):
        module_list = value.split(',')
        return query_set.filter(module_id__in=module_list)

    class Meta:
        model = Api
        fields = ['project', 'module']


class ApiFilter(django_filters.rest_framework.FilterSet):
    """
    接口列表过滤
    """
    project = django_filters.CharFilter(field_name='project_id', lookup_expr='exact')
    module = django_filters.CharFilter(method='module_filter')
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    url = django_filters.CharFilter(field_name='url', lookup_expr='icontains')
    method = django_filters.CharFilter(method='method_filter')
    creator = django_filters.CharFilter(method='creator_filter')

    def module_filter(self, query_set, name, value):
        module_list = value.split(',')
        return query_set.filter(module_id__in=module_list)

    def method_filter(self, queryset, name, value):
        method_list = value.split(',')
        return queryset.filter(method__in=method_list)

    def creator_filter(self, queryset, name, value):
        creator_list = value.split(',')
        return queryset.filter(creator_id__in=creator_list)

    class Meta:
        model = Api
        fields = ['project', 'module', 'name', 'url']
